<template>
  <div class="page-controller">
    <!-- 查询条件区 -->
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="tmplName" label="模版名称">
          <FIInput v-model="state.query.tmplName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="post" label="岗位">
          <FIAutoSelect
            v-model="state.queryPost"
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="1"
            apiUrl="/rm2/postMaint/query"
            :props="{ value: 'postEname', label: 'postCname' }"
            :displayKey="['postEname', 'postCname']"
            searchParam="postAName"
            multiple
          >
          </FIAutoSelect>
          <!-- <FISelect
            v-model="state.query.post"
            valueCustom="value"
            :options="[
              { value: '1', label: '是' },
              { value: '0', label: '否' },
            ]"
            clearable
          /> -->
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <!-- 查询结果列表区 -->
    <FITable
      ref="tableRef"
      class="box-radius2 margin-top20"
      title="记录集"
      :id="`result_${tableId}`"
      :readonly="true"
      :data="state.dataList"
      check-mode=""
      primaryKey="tmplId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      :insertable="false"
      :show-save-model="false"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="handleAction"
    >
      <template #headerBtn>
        <FIButton id="insert" border @click="showModelFn('add')"></FIButton>
      </template>
      <template #picBase64="{ scope }">
        <img
          v-if="scope.row.picBase64"
          class="pic-class"
          :src="scope.row.picBase64"
          @click="showImageDialog(scope.row)"
        />
        <!-- <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.picBase64"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="[scope.row.picBase64]"
            :initial-index="0"
            fit="cover"
            :z-index="999"
          /> -->
        <!-- <div>{{ scope.row.picBase64 }}</div> -->
      </template>
    </FITable>
    <el-image-viewer
      v-if="state.tempRowData.showPic"
      class="card-item__img"
      :url-list="[state.tempRowData.picBase64]"
      :zoom-rate="1.2"
      @close="state.tempRowData.showPic = false"
    >
    </el-image-viewer>

    <FIModel
      v-model="editVisible"
      :title="modelType == 'add' ? '新增' : '编辑'"
      width="600"
      :confirmLoading="state.confirmLoading"
      @confirm="handleAdd"
    >
      <FIForm>
        <FIFormItem prop="compType" label="模版名称">
          <FIInput v-model="state.rowObj.tmplName" clearable />
        </FIFormItem>
        <FIFormItem prop="compType" label="岗位">
          <FIAutoSelect
            v-model="state.savePost"
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="1"
            apiUrl="/rm2/postMaint/query"
            :props="{ value: 'postEname', label: 'postCname' }"
            :displayKey="['postEname', 'postCname']"
            searchParam="postAName"
            multiple
          >
          </FIAutoSelect>
        </FIFormItem>

        <FIFormItem prop="remark" label="描述">
          <FIInput v-model="state.rowObj.remark" :rows="3" type="textarea" />
        </FIFormItem>
      </FIForm>
    </FIModel>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIModel from '@/components/FIModel.vue'
import FIInput from '@/components/FIInput.vue'
import FITable from '@/components/FITable/index.vue'
import FIAutoSelect from '@/components/FIAutoSelect/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { useMessage } from '@/hooks/message' // 通用message消息提示框
import type { PageConfig, Column } from '@/types/components'
import { useRoute, useRouter } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
// 路由对象
const route = useRoute()
const router = useRouter()
// el-col span栅格占据的列数
const searchWrapperSpan = 8
// 表格是否显示加载中
const isTableLoading = ref(false)
// 页面编码
const tableId = 'GMOPComp'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const editVisible = ref(false)
const modelType = ref('add')
// 表格对象
const tableRef = ref(null)
const state = reactive({
  // 查询条件
  query: {
    tmplName: '',
    post: '',
    current: 1,
    size: 10,
  },
  queryPost: [],
  savePost: [],
  // 表格数据
  dataList: [],
  rowObj: {
    tmplName: '',
    post: '',
    remark: '',
    _isNew: 0,
  },
  confirmLoading: false,
  tempRowData: {
    showPic: false,
    picBase64: '',
  },
})

// 页面配置
const pageConfig: PageConfig = reactive({
  total: 0, // 总条数
  currentPage: 1, // 当前页码
})
// 表格列数据
const columns: Column[] = reactive([
  {
    label: '模版名称',
    prop: 'tmplName',
    align: 'center',
    minWidth: '150',
    editable: true,
    required: true,
  },

  {
    label: '适用岗位', // 列名
    prop: 'post', // 字段名称 对应列内容的字段名， 也可以使用 property属性
    align: 'center', // 列内容对齐方式
    minWidth: '140', // 列宽
    editable: true, // 是否可编辑
    editType: 'select', // 编辑类型
  },
  {
    label: '描述',
    prop: 'remark',
    align: 'center',
    minWidth: '130',
    editable: true,
  },

  {
    label: '创建人',
    prop: 'recCreator',
    align: 'center',
    minWidth: '120',
  },
  {
    label: '创建时间',
    prop: 'recCreateTime',
    align: 'center',
    minWidth: '160',
    editType: 'time-picker',
  },
  {
    label: '修改人',
    prop: 'recRevisor',
    align: 'center',
    minWidth: '120',
  },
  {
    label: '修改时间',
    prop: 'recReviseTime',
    align: 'center',
    minWidth: '160',
    editType: 'date-picker',
  },
  {
    label: '',
    prop: 'action',
    actionConfig: [
      { id: 'edit', type: 'edit' },
      { id: 'delete', type: 'delete' },
      { id: 'preview', type: 'preview' },
    ],
  },
])
// 选中列表集合
const checkedRows = ref([])
// 选中列表集合值改变回调函数
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
// 分页大小改变回调函数
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
// 分页页码改变回调函数
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}

// 搜索查询函数
const searchFn = (type?: string, columnsVal?: any) => {
  // 页面搜索数据组装
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  if (type == 'page') {
    state.query.current = pageConfig.currentPage
  } else {
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const apiUrl = proxy.$Button_api('query', route.name)
  state.query.post = state.queryPost.join(',')
  apiRequestPost(apiUrl, state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
// table保存提交
const handleAdd = () => {
  state.confirmLoading = true
  const apiUrl = proxy.$Button_api('insert', route.name)
  state.rowObj.post = state.savePost.join(',')
  apiRequestPost(apiUrl, state.rowObj)
    .then((res) => {
      state.confirmLoading = false
      if (res.data.success) {
        editVisible.value = false
        searchFn()
      }
    })
    .catch((error: any) => {
      state.confirmLoading = false
    })
}
// 删除函数
const deleteRow = (item) => {
  isTableLoading.value = true
  const apiUrl = proxy.$Button_api('delete', route.name)
  apiRequestPost(apiUrl, item)
    .then((res) => {
      isTableLoading.value = false
      searchFn()
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const handleAction = (item, rowData) => {
  if (item.type === 'edit') {
    // editVisible.value = true
    state.rowObj = rowData
    router.push({
      name: 'GMOPTmplEdit',
      query: {
        id: rowData.tmplId,
      },
    })
    // showModelFn('edit')
  } else if (item.type === 'delete') {
    deleteRow(rowData)
  } else if (item.type === 'preview') {
  }
}
const showModelFn = (type = 'add') => {
  router.push({
    name: 'GMOPTmplEdit',
    query: {
      id: '',
    },
  })
  //   editVisible.value = true
  //   modelType.value = type
  //   if (type === 'add') {
  //     state.rowObj = {
  //       tmplName: '',
  //       post: '',
  //       remark: '',
  //       _isNew: 1,
  //     }
  //   } else {
  //     state.rowObj._isNew = 0
  //   }
}
const showImageDialog = (data) => {
  state.tempRowData.picBase64 = data.picBase64
  state.tempRowData.showPic = true
}

onMounted(() => {
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  searchFn()
})
</script>
<style lang="less" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.pic-class {
  width: 85px;
  height: 60px;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
